<script lang='ts' setup>
import { reactive, defineAsyncComponent, ref, computed} from 'vue'
import { Search,} from '@element-plus/icons-vue'  
import { ElMessageBox, ElMessage } from 'element-plus'
import { api as ViewerApi } from 'v-viewer'
const AddCategoryTree = defineAsyncComponent(() => import('/@/components/information/AddCategoryTree.vue'))
const UploadImage = defineAsyncComponent(() => import('/@/components/information/UploadImage.vue'))

const emit = defineEmits(['selectFun'])

export interface Tree {
    id: number
    label: string
    pid: number
    children?: Tree[]
    value?: number,
}

const state = reactive({
    isShowDialog: false,
    isArr: null,
    name: '',
    currentCategory: 0,
    currentImg: 0,
    move: '',
    count: 0,
    type: 1,
    category: [
        { id: 222, name: '全部图片', },
        { id: 42, name: '首图', },
        { id: 522, name: '视频', }, 
    ],
    informationList: [
        {type: 'img', id: 5, src: 'https://static9.meton.vip/11410_1694671989002.jpg', name: '图片名称1', edit: false},
        {type: 'img', id: 9, src: 'https://static9.meton.vip/11410_1694671807216.png', name: '图片名称2', edit: false},
        {type: 'img', id: 2, src: 'https://static9.meton.vip/11410_1694671575110.png', name: '图片名称3', edit: false},
        {type: 'img', id: 33, src: 'https://static9.meton.vip/10715_1669801186798.jpg', name: '图片名称4', edit: false},
        {type: 'img', id: 1, src: 'https://static9.meton.vip/10715_1689650118134.jpg', name: '图片名称5', edit: false},
        {type: 'img', id: 87, src: 'https://static9.meton.vip/10715_1689652773180.jpg', name: '图片名称6', edit: false},
        {type: 'img', id: 27, src: 'https://static9.meton.vip/10715_1685496402659.jpg', name: '图片名称7', edit: false},
    ],
    setList: new Set<string>(),
    treeData: [
        {
            id: 2,
            label: 'Level one 2',
            pid: 0,
            children: [
                {
                    id: 5,
                    label: 'Level two 2-1',
                    pid: 2
                },
                {
                    id: 6,
                    label: 'Level two 2-2',
                    pid: 2
                },
            ],
        }
    ] as Array<Tree>,
    srcList: null as Array<string> | null,
    previewIndex: 0,
    
}) 
// const sortArr = ref<Array<number>>(new Array(state.informationList.length).fill(0))
const props = withDefaults(defineProps<{ 
    modelValue: boolean, 
}>(), {
    modelValue: false
})
// const srcList = computed(() => {
//     return state.informationList.map(ele => ele.src)
// })

const uploadImageVisibel = ref(false)
const categoryVisibel = ref(false)
const AddCategoryTreeNode = ref()
const uploadImageNode = ref()


const toggleCategory = async (index: number) => {
	state.currentCategory = index
}

const confirmImg = async () => {
	if(state.setList.size === 0) {
        return ElMessage({
            message: '请选择图片',
            type: 'warning',
        })
    }else{
        emit('selectFun', [...state.setList]);
        state.isShowDialog = false;
    }
}

// 打开弹窗
const openDialog = (isArr:Number) => {
    state.isArr = isArr;
    // 清空选中项
    state.setList.clear()
	state.isShowDialog = true;
};

const closeDialog = () => {
    state.isShowDialog = false;
}

// 图片选择  
const selectImg = (src: string) => {
    if(state.setList.has(src)) {
        state.setList.delete(src)
        state.count --
    } else {
        // 单文件
        if(state.isArr == 0 && state.setList.size != 0){
            return ElMessage({
                type: 'warning',
                message: '最多只能选一张图片',
            })
        }
        state.setList.add(src)
        state.count ++
    }
    if(state.setList.size === 0) {
        state.count = 0
    }
};

const uploadImg = async () => uploadImageVisibel.value = true;

const pageNation = reactive({
    pageNum: 1,
    pageSize: 20,
    total: 0
})

const deleteHandle = (row: any ) => {
	ElMessageBox.confirm(
    '确定删除选中的图片 ?',
    '提示',
		{
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		}
	)
	.then(() => {
		 
	})
	.catch(() => {
		 
    })
}

const handleCommand = (e: 'a' | 'e' | 'd', data: Tree) => {
    if(e === 'a') {
        // const newChild = { id: Date.now(), label: 'testtest', children: [], pid: data.id }
        // if (!data.children) {
        //     data.children = []
        // }
        // data.children.push(newChild)
        // state.treeData = [...state.treeData]
        categoryVisibel.value = true
    }
    if(e === 'e') {
        categoryVisibel.value = true
        AddCategoryTreeNode.value.setInitData(666, [3, 99])
    }
    if(e === 'd') {
        ElMessageBox.confirm(
        '确定删除该分类 ?',
        '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        .then(() => {
            
        })
        .catch(() => {
            
        })
    }
    console.log(e, data);
    
}

const confirmCategory = (obj: {name: string, id: Array<number>}) => {
    console.log(obj);
}

const oprationHandle = (item: any, index: number, type: 'd' | 'r' | 'p') => {
    if(type === 'd') {
        ElMessageBox.confirm(
        '确定删除该图片 ?',
        '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        .then(() => {
            
        })
        .catch(() => {
            
        })
    }
    if(type === 'r') {
        item.edit = true
    }

    if(type === 'p') {
        state.srcList = state.informationList.map(e => e.src)
        ViewerApi({
            options: {
                initialViewIndex: index
            },
            images: state.srcList 
        });
    }
}
const editBlur = (event: any, item: any, index: number) => {
    state.informationList[index].edit = false
}

const moveToHandle = (event: any) => {
    console.log(event);
    
}


/**
 * 分页函数
 */
const handleSizeChange = () => {}
const handleCurrentChange = () => {}

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<template>
    <main> 
        <el-dialog v-model="state.isShowDialog" append-to-body title="上传图片" center @close="closeDialog">
            <section class="selector-img-content">
                <section class="left-nav">
                    <section>
                        <el-tree :data="state.treeData"   node-key="id" default-expand-all :expand-on-click-node="false">
                            <template #default="{ node, data }">
                                <section class="custom-tree-node flex-c" style="justify-content: space-between; flex: 1; padding: 8px 0;">
                                    <section class="flex-c">
                                        <svg v-if="data.pid <= 0" t="1705979483053" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4711" width="16" height="16"><path d="M918.673 883H104.327C82.578 883 65 867.368 65 848.027V276.973C65 257.632 82.578 242 104.327 242h814.346C940.422 242 958 257.632 958 276.973v571.054C958 867.28 940.323 883 918.673 883z" fill="#FFE9B4" p-id="4712"></path><path d="M512 411H65V210.37C65 188.597 82.598 171 104.371 171h305.92c17.4 0 32.71 11.334 37.681 28.036L512 411z" fill="#FFB02C" p-id="4713"></path><path d="M918.673 883H104.327C82.578 883 65 865.42 65 843.668V335.332C65 313.58 82.578 296 104.327 296h814.346C940.422 296 958 313.58 958 335.332v508.336C958 865.32 940.323 883 918.673 883z" fill="#FFCA28" p-id="4714"></path></svg>
                                        &nbsp;<span>{{ node.label }}</span>
                                    </section>
                                    <span>
                                        <el-dropdown @command="handleCommand($event, data)">
                                            <span class="el-dropdown-link">
                                                <el-icon class="el-icon--right">
                                                    <svg t="1705979906658" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5767" width="16" height="16"><path d="M223.962372 607.897867c-52.980346 0-95.983874-43.003528-95.983874-95.983874s43.003528-95.983874 95.983874-95.983874 95.983874 43.003528 95.983874 95.983874S276.942718 607.897867 223.962372 607.897867z" fill="#575B66" p-id="5768"></path><path d="M511.913993 607.897867c-52.980346 0-95.983874-43.003528-95.983874-95.983874s43.003528-95.983874 95.983874-95.983874 95.983874 43.003528 95.983874 95.983874S564.894339 607.897867 511.913993 607.897867z" fill="#575B66" p-id="5769"></path><path d="M800.037628 607.897867c-52.980346 0-95.983874-43.003528-95.983874-95.983874s43.003528-95.983874 95.983874-95.983874 95.983874 43.003528 95.983874 95.983874S852.84596 607.897867 800.037628 607.897867z" fill="#575B66" p-id="5770"></path></svg>
                                                </el-icon>
                                            </span>
                                            <template #dropdown>
                                                <el-dropdown-menu>
                                                    <el-dropdown-item command="a">添加分类</el-dropdown-item>
                                                    <el-dropdown-item command="e">编辑分类</el-dropdown-item>
                                                    <el-dropdown-item command="d">删除分类</el-dropdown-item> 
                                                </el-dropdown-menu>
                                            </template>
                                        </el-dropdown> 
                                    </span>
                                </section>
                            </template>
                        </el-tree>
                    </section>
                </section>
                <section class="right-img-wrapper">
                    <section style="display: flex; align-items: center;">
                        <el-button type="primary" :disabled="state.setList.size === 0" size="default" @click="confirmImg">使用选中图片</el-button>
                        <el-button type="primary" size="default" @click="uploadImg">上传图片</el-button>
                        <el-button type="danger" size="default" @click="deleteHandle">删除图片</el-button>&emsp;
                        <el-cascader :options="state.treeData" placeholder="移动图片至"
                         size="default" :props="{value: 'id', checkStrictly: true,}" clearable
                         @change="moveToHandle"
                          />
                    </section>
                    <section class="goods-img-list">
                        <section class="goods-img-item mr20 mt20" v-for="(i, index) of state.informationList" :key="index">
                            <section style="position: relative;" @click.prevent.stop="selectImg(i.src)"> 
                                <img :src="i.src" :class="['goods-img', state.setList.has(i.src) ? 'active-img' : '']" style="" alt="">
                                <!-- <i class="img-index" v-show="state.setList.has(i.src)"> 
                                    {{ state.setList.has(i.src) |  }}
                                </i> -->
                            </section>
                            <p v-show="!i.edit" class="goods-img-name">{{ i.name }}</p> 
                            <section v-show="i.edit">
                                <el-input v-model="i.name" clearable size="small" @blur="editBlur($event, i, index)" style="width: 100px;margin: 0 5px;"></el-input>
                            </section>
                            <section class="opration-wrapper flex-c">
                                <span @click="oprationHandle(i, index, 'd')">删除</span>
                                <span @click="oprationHandle(i, index, 'r')">重命名</span>
                                <span @click="oprationHandle(i, index, 'p')">查看</span>
                            </section>
                        </section>
                    </section>
                    <section class="mt15">
                        <el-row justify="end">
                            <el-col :span="24" class="flex-end-center">
                                <el-pagination
                                v-model:current-page="pageNation.pageNum"
                                v-model:page-size="pageNation.pageSize"
                                :page-sizes="[10, 20, 30]"  
                                :background="true"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="pageNation.total"
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                />
                            </el-col>
                        </el-row> 
                    </section>
                </section>
            </section> 
        </el-dialog>
        <AddCategoryTree v-model="categoryVisibel" @confirmCategory="confirmCategory" ref="AddCategoryTreeNode"  />
        <UploadImage v-model="uploadImageVisibel" ref="uploadImageNode"  />
    </main>
</template>

<style lang='scss' scoped>
:deep() {
    .el-tree-node__content {
        height: auto !important;
    } 
}
.flex-c {
    display: flex;
    align-items: center;
}
    .selector-img-content{
        display: flex;
        .left-nav{
            width: 200px;
            height: 400px;
            // background-color: #f5f5f5;
            margin-right: 30px;
            .category-item{
                padding: 10px 5px;
                cursor: pointer;
                transition: all 0.3s;
                display: flex;
                align-items: center;
                justify-content: space-between;
                span{ opacity: .5;}
                &:hover {
                    background-color: #f0f0f0;
                }
                &:hover span{
                    opacity: 1;
                }
            }
            .active-c{
                background-color: #f0f0f0;
                color: #409EFF;
            }
        }
        .right-img-wrapper{
            flex: 1;
            border-left: 1px solid #ededed;
            padding-left: 15px;
            .goods-img-item{ 
                .img-index{
                    position: absolute;
                    bottom: 8px;
                    right: 8px;
                    width: 20px;
                    height: 20px;
                    font-size: 13px;
                    color: #fff;
                    background-color: #217ef7;
                    text-align: center;
                    line-height: 20px;
                    border-radius: 50%;
                }
                &:hover span {
                    display: block;
                }
            }
            .goods-img-list{
                display: flex;
                flex-wrap: wrap;
            }
            .goods-img-name{
                width: 110px;
                text-align: center;
                overflow:hidden;
                text-overflow:ellipsis;
                white-space:nowrap
            }
            .goods-img{
                width: 110px;
                height: 110px; 
                object-fit: cover; 
                border-radius: 6px;
                border: 2px solid #ffffff;
                cursor: pointer;
                padding: 4px;
                border: 1px solid #fff;
                &:hover {
                    border: 1px solid #409EFF;
                }
            }
            .active-img {
                border: 1px solid #409EFF;
            }
        }
        .opration-wrapper {
            font-size: 12px; 
            color: #409EFF;
            text-align: center;
            height: 20px;
            justify-content: space-between;
            margin: 0 5px;
            
            span{
                cursor: pointer;
                display: none;
            }
        }
    }
</style>